package com.lancer.cloud.generator.service.impl;

import com.lancer.cloud.common.base.service.impl.BaseServiceImpl;
import com.lancer.cloud.generator.mapper.ColumnInfoMapper;
import com.lancer.cloud.generator.model.dto.BuildConfigDto;
import com.lancer.cloud.generator.model.entity.ColumnInfo;
import com.lancer.cloud.generator.model.entity.TableInfo;
import com.lancer.cloud.generator.service.SysGenerationService;
import com.lancer.cloud.generator.service.TableInfoService;
import com.lancer.cloud.generator.util.CodeGeneratorUtil;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 系统代码生成服务
 *
 * caijinbang
 * @date 2019-06-17 12:28
 */
@Service
public class SysGenerationServiceImpl extends BaseServiceImpl<ColumnInfoMapper, ColumnInfo> implements SysGenerationService {

    @Autowired
    private TableInfoService tableInfoService;

    @Autowired
    private ColumnInfoMapper columnInfoMapper;

    /**
     * 根据表名生成代码
     */
    @Override
    public byte[] genCodeByTableName(BuildConfigDto buildConfigDTO) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : buildConfigDTO.getTableName()) {
            //查询表信息
            TableInfo table = tableInfoService.findTableInfoByName(tableName);
            //查询列信息
            List<ColumnInfo> columns = columnInfoMapper.listByTableName(tableName);
            //生成代码
            CodeGeneratorUtil.generatorCode(buildConfigDTO,table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();

    }
}
